import React, { Component } from 'react'
import { Button, Col, Icon, Popconfirm, Row, Table } from 'antd'
import '../../less/index.less'
import '../../less/program-list.less'
import { withRouter } from 'react-router-dom'
import EditableCell from '../common/editable-cell'
import { connect } from 'react-redux'
import ReactDragListView from 'react-drag-listview'
import ShowToStudentCell from './show-student-cell'
import * as taskActions from '../../actions/task'
import { TwsReactMarkdownEditor } from 'tws-antd'
import { getUploadUrl } from '../../constant/upload-url'
import { convertContent } from '../../constant/lang-util'

class Task extends Component {
  constructor (props) {
    super(props)
    this.state = {
      expandIconAsCell: false,
      expandRowByClick: true,
      expandedRowKeys: [],
      content: '',
      contentIcon: 'edit',
      editId: 0
    }
  }

  onDelete (taskId) {
    this.props.deleteTask(this.props.programId, this.props.topicId, taskId)
  }

  handleAdd () {
    const newTask = {
      title: '',
      deadLine: '2017-3-2',
      programId: this.props.programId,
      topicId: this.props.topicId,
      type: ``
    }
    this.props.addTask(this.props.programId, this.props.topicId, newTask)
  }

  onCellChange (value, type, task) {
    task[type] = value
    this.props.editTask(this.props.programId, this.props.topicId, task)
  }

  goFeedBack (taskId) {
    const {location} = this.props

    this.props.history.push(location.pathname + '/task/' + taskId + '/suggestion')
  }

  addDescription (task) {
    const content = this.state.content
    this.onCellChange(content, 'content', task)
    this.setState({
      expandedRowKeys: [],
      contentIcon: 'edit',
      content: ''
    })
  }

  operateDescription (record) {
    this.onExpandedRowsChange(record)
    this.setState({
      contentIcon: 'check',
      editId: record.id,
      content: record.content
    })
  }

  onExpandedRowsChange (rows) {
    this.setState({
      expandedRowKeys: [rows.id]
    })
  }

  editorContent (content) {
    this.setState({content})
  }

  expandedRowRender (settings, record) {
    return <div>
      <TwsReactMarkdownEditor
        action={getUploadUrl(settings.appContextPath)}
        value={record.content}
        onChange={this.editorContent.bind(this)}
      />
      <Button className='margin-t-2' type='primary'
        onClick={this.addDescription.bind(this, record)}>{convertContent('提交')}</Button>
    </div>
  }

  switchIcon (record) {
    if (this.state.contentIcon === 'check' && record.id === this.state.editId) {
      return <Icon type='check' onClick={this.addDescription.bind(this, record)} />
    } else {
      return <Icon type='edit' onClick={this.operateDescription.bind(this, record)} />
    }
  }

  addAssignment (taskId) {
    window.location.href = `./index.html#/program/${this.props.programId}/task/${taskId}`
  }

  toDiff (taskId) {
    const {settings} = this.props
    const {diffUrl,appContextPath} = settings
    if (!appContextPath) {
      window.location.href = `http://localhost:3000/#/tasks/${taskId}/history`
      return
    }
    if (appContextPath === '/learn') {
      window.location.href = `https://school.thoughtworks.cn${diffUrl}#/tasks/${taskId}/history`
      return
    }

    window.location.href = `https://staging.school.thoughtworks.cn${diffUrl}#/tasks/${taskId}/history`
  }

  render () {
    const {tasks, operationEnable, settings, isReadOnly} = this.props
    const {expandRowByClick, expandIconAsCell, expandedRowKeys} = this.state
    const columns = [{
      title: convertContent('任务卡名称'),
      dataIndex: 'title',
      render: (text, record) => {
        return (
          <EditableCell
            isTask
            isReadOnly={isReadOnly}
            value={text}
            id={record.id}
            onChange={value => this.onCellChange(value, 'title', record)}
          />)
      }
    }, {
      title: convertContent('任务描述'),
      dataIndex: 'content',
      render: (text, record) => {
        return <Row>
          <Col span={22} className='col' style={{width: 110}}>
            <span>{text}</span>
          </Col>
          {
            isReadOnly
              ? ''
              : <Col span={1} offset={1} style={{float: 'right'}}>
                {this.switchIcon(record)}
              </Col>
          }
        </Row>
      }
    }, {
      title: convertContent('答疑链接'),
      dataIndex: 'link',
      render: (text, record) => {
        return (
          <EditableCell
            isReadOnly={isReadOnly}
            isTaskLink
            value={text}
            id={record.id}
            changeShow={() => {}}
            onChange={value => this.onCellChange(value, 'link', record)}
          />)
      }
    },
    {
      title: convertContent('状态'),
      dataIndex: 'status',
      render: (text, record) => {
        return (
          <span>
            <ShowToStudentCell
              readOnly
              visibility={record.visible ? record.visible : 0}
              changeTopicVisible={this.props.changeTopicVisible}
              id={record.id}
              programId={record.programId} />
          </span>)
      }
    },
    {
      title: convertContent('操作'),
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          <div className='task-box'>
            {
                isReadOnly
                  ? ''
                  : <span><span>
                    <ShowToStudentCell
                      changeTaskVisible={this.props.changeTaskVisible}
                      topicId={record.topicId}
                      programId={record.programId}
                      type='task'
                      visibility={record.visible ? record.visible : 0}
                      id={record.id} />
                  </span>
                    <span className='ant-divider' />

                    <span className='margin-l-1'>
                      {tasks.length >= 1 ? (
                        <Popconfirm title={convertContent('确定删除吗?')} onConfirm={() => this.onDelete(record.id)}>
                          <a href=''>{convertContent('删除')}</a>
                        </Popconfirm>
                      ) : null}
                    </span>
                    <span className='ant-divider' />
                    <span className='margin-l-1'>
                      <a className='drag-handle'>{convertContent('拖拽排序')}</a>
                    </span>
                    <span className='ant-divider' />
                  </span>
              }

            <a className='margin-l-1' onClick={this.goFeedBack.bind(this, record.id)}>{convertContent('吐槽管理')}</a>
            <span className='ant-divider' />
            <a className='margin-l-1' onClick={this.toDiff.bind(this, record.id)}>Diff</a>
            <span className='ant-divider' />
            <a className='margin-l-1' onClick={this.addAssignment.bind(this, record.id)}>{convertContent('管理作业')}</a>
          </div>
        )
      }
    }]

    const that = this
    const drag = {
      onDragEnd (fromIndex, toIndex) {
        const data = that.props.tasks
        const item = data.splice(fromIndex, 1)[0]
        data.splice(toIndex, 0, item)
        that.props.dragSort(data, that.props.programId, that.props.topicId)
      },
      nodeSelector: '.task-row',
      handleSelector: 'a'
    }

    const rowSelection = {
      selectedRowKeys: this.props.selectedRowKeys,
      onSelect: (record, selected) => {
        const taskId = record.id
        this.props.selectTaskRows([taskId], selected)
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const taskIds = changeRows.map(row => row.id)
        this.props.selectTaskRows(taskIds, selected)
      }
    }

    return (
      <div className='margin-t-4'>
        <ReactDragListView {...drag}>
          <Table dataSource={tasks} columns={columns} pagination={false} className='task'
            rowSelection={operationEnable ? rowSelection : null}
            expandRowByClick={expandRowByClick}
            expandIconAsCell={expandIconAsCell}
            expandedRowKeys={expandedRowKeys}
            rowClassName='task-row'
            expandedRowRender={this.expandedRowRender.bind(this, settings)}
            rowKey={record => record.id}
            title={() => <p>
              {
                     isReadOnly
                       ? ''
                       : <a onClick={this.handleAdd.bind(this)}>{convertContent('新增任务卡')}</a>
                   }
            </p>} />
        </ReactDragListView>
      </div>
    )
  }
}

const mapStateToProps = state => ({
  currentTopicTasks: state.instructorCurrentTopicTasks,
  settings: state.settings
})

const mapDispatchToProps = dispatch => ({
  addTask: (programId, topicId, newTask) => dispatch(taskActions.addTask(programId, topicId, newTask)),
  editTask: (programId, topicId, task) => dispatch(taskActions.editTask(programId, topicId, task)),
  deleteTask: (programId, topicId, taskId) => dispatch(taskActions.deleteTask(programId, topicId, taskId)),
  dragSort: (data, programId, topicId) => dispatch(taskActions.dragSort(data, programId, topicId)),
  changeTaskVisible: (visibility, id, programId, topicId) => dispatch(taskActions.changeTaskVisible(visibility, id, programId, topicId))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Task))
